var db = require('../model');
var utils = require('../utils');
var xss = require('xss');

module.exports = {
  my: function(req, res, next) {
    var paging = utils.getPaging(req.query);
    var id = req.decoded.data._id;
    db.diary.find({
      userid:id
    })
    .populate({
      path:'userid',
      model:db.user,
      select:'_id nick avatar'
    })
    .populate({
      path:'notebook',
      model:db.notebook,
      select:'name bgcolor'
    })
    .sort({created_at:-1})
    .skip(paging.skip)
    .limit(paging.count)
    .lean()
    .then(ret => {
      ret.forEach(item => {
        utils.feedItemFix(item);
      });
      utils.fixUser(ret);
      res.json(utils.formatResult(ret));
    },
    err => {
      next(err);
    });
  },
  goods: function(req,res,next){
    var paging = utils.getPaging(req.query);
    db.diary.find({
      privacy: 0,
      content:/<img [^>]*src=['"]([^'"]+)[^>]*>/gi
    }).$where('this.content.length > 100')
    .populate({
      path:'userid',
      model:db.user,
      select:'_id nick avatar'
    })
    .populate({
      path:'notebook',
      model:db.notebook,
      select:'name bgcolor'
    })
    .sort({created_at:-1}).skip(paging.skip).limit(paging.count).lean().then(ret => {
      ret.forEach(item => {
        utils.feedItemFix(item);
      }); 
      utils.fixUser(ret);
      res.json(utils.formatResult(ret));
    },
    err => {
      next(err);
    });
  },
  followers:function(req,res,next){
    var paging = utils.getPaging(req.query);
    var ids = req.decoded.data.firends;
    db.diary.find({
      privacy: 0,
      userid:{
        '$in':ids 
      }
    }).$where('this.content.length > 100')
    .populate({
      path:'userid',
      model:db.user,
      select:'_id nick avatar'
    })
    .populate({
      path:'notebook',
      model:db.notebook,
      select:'name bgcolor'
    })
    .sort({created_at:-1}).skip(paging.skip).limit(paging.count).lean().then(ret => {
      ret.forEach(item => {
        utils.feedItemFix(item);
      });
      utils.fixUser(ret);
      res.json(utils.formatResult(ret));
    },
    err => {
      next(err);
    });
  },
  remove:function(req,res,next){
    var id = req.body.diaryid,
    uid = req.decoded.data._id;
    db.diary.find({
      _id:id,
      userid:uid
    }).remove().then(ret=>{
      res.json(utils.formatResult(ret));
      db.user.update({_id:uid},{
        '$inc':{
          'diarycount':-1
        }
      }).then();
      db.comment.find({related_id:id}).remove().then();
    },next);
  },
  save:function(req,res,next){
    var bookid = req.body.bookid,
      content = req.body.content,
      location = req.body.location,
      weather = req.body.weather,
      mood = req.body.mood,
      privacy = req.body.privacy || 0,
      forbid = req.body.forbid || 0;
    content = xss(content, {
        whiteList: {
          p: [],
          a: ['href', 'target'],
          img: ['src', 'data-url', 'data-type', 'width', 'height'],
          b: [],
          i: [],
          u: [],
          strike: [],
          blockquote: [],
          pre: [],
          hr: []
        },
        stripIgnoreTag: true
    });
    var savedata = {
      content: content,
      notebook: bookid,
      userid: req.decoded.data._id,
      //  filelist: filelist,
      privacy: req.decoded.data.emailnotallow ? 1 : privacy,
      forbid: forbid,
      assist:[],
      commentcount: 0,
      view: 0,
      created_at:Date.now()
    };
    if (weather) savedata['weather'] = weather;
    if (mood) savedata['mood'] = mood;
    if (location) savedata['location'] = location;
    db.ids.findOneAndUpdate({
      name:'diary'
    },{
      '$inc':{id:1}
    }).then(ret=>{
      savedata.id = ret.id;
      new db.diary(savedata).save().then(ret=>{
        res.json(utils.formatResult({status:'success'}));
      },next);
      db.user.update({_id:req.decoded.data._id},{
        '$inc':{
          'diarycount':1
        }
      }).then();
    },next);
  }
}
